package com.lgmshare.component.utils;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.res.Resources;
import android.os.Build;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import androidx.annotation.ArrayRes;
import androidx.annotation.ColorRes;
import androidx.annotation.DimenRes;
import androidx.annotation.StringRes;

import com.lgmshare.component.app.LaraApplication;
import com.lgmshare.component.utils.thread.ThreadPool;

/**
 * 页面相关工具类集合
 */
public class UIUtils {

    public static Toast mToast;
    public static int screenWidth;
    public static int screenHeight;
    public static int screenMin;// 宽高中，小的一边
    public static int screenMax;// 宽高中，较大的值
    public static float density;
    public static float scaledDensity;
    public static float xdpi;
    public static float ydpi;
    public static int densityDpi;
    public static int statusBarHeight;
    public static int navigationBarHeight;

    private UIUtils() {
    }

    //---------------------------------------------------------------------

    public static void showToast(@StringRes int resId) {
        showToast(getString(resId));
    }

    public static void showToast(String msg) {
        showToast(msg, Toast.LENGTH_SHORT);
    }

    public static void showToastLong(@StringRes int resId) {
        showToastLong(getString(resId));
    }

    public static void showToastLong(String msg) {
        showToast(msg, Toast.LENGTH_LONG);
    }

    public static void showToast(@StringRes int resId, int duration) {
        showToast(getString(resId), duration);
    }

    public static void showToast(String msg, int duration) {
        // 全局单例Toast的使用在Android9.0有例外，当前Toast还未消失时弹出下一个Toast，会导致当前Toast消失，
        // 并且下一个Toast也不会显示，之后短时间内弹出的Toast也不会显示
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.P) {
            Toast.makeText(getContext(), msg, duration).show();
        } else {
            if (mToast == null) {
                mToast = Toast.makeText(getContext(), msg, duration);
            } else {
                mToast.setText(msg);
                mToast.setDuration(duration);
            }
            mToast.show();
        }
    }

    public static void showToast(View view, int duration) {
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.P) {
            Toast.makeText(getContext(), "", duration).show();
        } else {
            if (mToast == null) {
                mToast = Toast.makeText(getContext(), "", duration);
                mToast.setView(view);
            } else {
                mToast.setView(view);
                mToast.setDuration(duration);
            }
            mToast.show();
        }
    }

    //---------------------------------------------------------------------

    /**
     * 得到上下文
     *
     * @return
     */
    public static Context getContext() {
        return LaraApplication.getContext();
    }

    /**
     * 得到resources对象
     *
     * @return
     */
    public static Resources getResource() {
        return getContext().getResources();
    }

    /**
     * 得到string.xml中的字符串
     *
     * @param id
     * @return
     */
    public static String getString(@StringRes int id) {
        return getResource().getString(id);
    }

    /**
     * 得到string.xml中的字符串，带点位符
     *
     * @return
     */
    public static String getString(@StringRes int id, Object... formatArgs) {
        return getResource().getString(id, formatArgs);
    }

    /**
     * 得到string.xml中和字符串数组
     *
     * @param id
     * @return
     */
    public static String[] getStringArray(@ArrayRes int id) {
        return getResource().getStringArray(id);
    }

    /**
     * 得到colors.xml中的颜色
     *
     * @param id
     * @return
     */
    public static int getColor(@ColorRes int id) {
        return getResource().getColor(id);
    }

    /**
     * 得到主线程Handler
     *
     * @return
     */
    public static Handler getMainThreadHandler() {
        return LaraApplication.getMainThreadHandler();
    }

    /**
     * 得到主线程id
     *
     * @return
     */
    public static long getMainThreadId() {
        return LaraApplication.getMainThreadId();
    }

    /**
     * 在主线程中执行一个任务
     *
     * @param task
     */
    public static void runOnUiThread(Runnable task) {
        int curThreadId = android.os.Process.myTid();
        // 如果当前线程是主线程
        if (curThreadId == getMainThreadId()) {
            task.run();
        } else {
            // 如果当前线程不是主线程
            getMainThreadHandler().post(task);
        }
    }

    /**
     * 在主线程中延迟执行任务
     *
     * @param task
     * @param delayMillis
     */
    public static void runOnUiThread(Runnable task, long delayMillis) {
        getMainThreadHandler().postDelayed(task, delayMillis);
    }

    /**
     * 在异步线程中执行任务
     *
     * @param task
     */
    public static void runOnAsyncThread(Runnable task) {
        int curThreadId = android.os.Process.myTid();
        // 如果当前线程是主线程
        if (curThreadId == getMainThreadId()) {
            ThreadPool.runOnAsyncTask(task);
        } else {
            // 如果当前线程不是主线程
            task.run();
        }
    }

    /**
     * 移除任务
     */
    public static void removeTask(Runnable task) {
        getMainThreadHandler().removeCallbacks(task);
    }

    //---------------------------------------------------------------------

    private static void initInfo(Context context) {
        if (null == context) {
            return;
        }
        DisplayMetrics dm = context.getApplicationContext().getResources().getDisplayMetrics();
        screenWidth = dm.widthPixels;
        screenHeight = dm.heightPixels;
        screenMin = (screenWidth > screenHeight) ? screenHeight : screenWidth;
        screenMax = (screenWidth < screenHeight) ? screenHeight : screenWidth;
        density = dm.density;
        densityDpi = dm.densityDpi;
        scaledDensity = dm.scaledDensity;
        xdpi = dm.xdpi;
        ydpi = dm.ydpi;
        statusBarHeight = getStatusBarHeight();
        navigationBarHeight = getNavigationBarHeight();
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     *
     * @param dpValue
     * @return
     */
    public static int dipToPx(float dpValue) {
        if (density == 0) {
            density = getResource().getDisplayMetrics().density;
        }
        return Math.round(dpValue * density);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     *
     * @param pxValue
     * @return
     */
    public static int pxToDip(float pxValue) {
        if (density == 0) {
            density = getResource().getDisplayMetrics().density;
        }
        return Math.round(pxValue / density);
    }

    /**
     * 根据手机的分辨率从 sp 的单位 转成为 px
     *
     * @param spValue
     * @return
     */
    public static int spToPx(float spValue) {
        if (scaledDensity == 0) {
            scaledDensity = getResource().getDisplayMetrics().scaledDensity;
        }
        return Math.round(spValue * scaledDensity);
    }

    /**
     * px转sp
     *
     * @param pxValue px值
     * @return sp值
     */
    public static int pxToSp(float pxValue) {
        if (scaledDensity == 0) {
            scaledDensity = getResource().getDisplayMetrics().scaledDensity;
        }
        return Math.round(pxValue / scaledDensity);
    }

    /**
     * 获取资源像素大小
     *
     * @param id
     * @return
     */
    public static int getDimensionPixelSize(@DimenRes int id) {
        return getResource().getDimensionPixelSize(id);
    }

    /**
     * 获取屏幕宽度
     */
    public static int getDisplayWidth() {
        if (screenWidth == 0) {
            initInfo(getContext());
        }
        return screenWidth;
    }

    /**
     * 获取屏幕高度
     */
    public static int getDisplayHeight() {
        if (screenHeight == 0) {
            initInfo(getContext());
        }
        return screenHeight;
    }

    /**
     * 获取系统状态栏高度(通过系统尺寸资源获取)
     *
     * @return
     */
    public static int getStatusBarHeight() {
        if (statusBarHeight > 0) {
            return statusBarHeight;
        }
        int resourceId = getResource().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            return getResource().getDimensionPixelSize(resourceId);
        }
        return 0;
    }

    /**
     * 获取系统标题栏高度(通过系统尺寸资源获取)
     *
     * @return
     */
    public static int getNavigationBarHeight() {
        if (navigationBarHeight > 0) {
            return navigationBarHeight;
        }
        if (hasNavigationBar()) {
            int resourceId = getResource().getIdentifier("navigation_bar_height", "dimen", "android");
            if (resourceId > 0) {
                return getResource().getDimensionPixelSize(resourceId);
            }
        }
        return 0;
    }

    /**
     * 是否有显示系统底部导航栏
     *
     * @return
     */
    public static boolean hasNavigationBar() {
        int id = getResource().getIdentifier("config_showNavigationBar", "bool", "android");
        return (id > 0) && getResource().getBoolean(id);
    }

    /**
     * 复制文本到剪贴板
     *
     * @param text
     */
    public static void copyTextToClip(String text) {
        //创建ClipData对象
        ClipboardManager clipboardManager = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
        //添加ClipData对象到剪切板中
        clipboardManager.setPrimaryClip(ClipData.newPlainText("LabelText", text));
    }

    /**
     * 获取剪贴板的文本
     *
     * @return 剪贴板的文本
     */
    public static String getTextFromClip() {
        ClipboardManager clipboardManager = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
        //判断剪切版时候有内容
        if (!clipboardManager.hasPrimaryClip())
            return "";
        ClipData clipData = clipboardManager.getPrimaryClip();
        if (clipData != null && clipData.getItemCount() > 0) {
            return clipData.getItemAt(0).getText().toString();
        }
        return "";
    }

    /**
     * 动态显示软键盘
     *
     * @param activity activity
     */
    public static void showSoftInput(final Activity activity) {
        View view = activity.getCurrentFocus();
        if (view == null) view = new View(activity);
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
        if (imm == null) return;
        imm.showSoftInput(view, InputMethodManager.SHOW_FORCED);
    }

    /**
     * 动态显示软键盘
     *
     * @param view 视图
     */
    public static void showSoftInput(final View view) {
        view.setFocusable(true);
        view.setFocusableInTouchMode(true);
        view.requestFocus();
        InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm == null) return;
        imm.showSoftInput(view, InputMethodManager.SHOW_FORCED);
    }

    /**
     * 动态隐藏软键盘
     *
     * @param activity activity
     */
    public static void hideInputMethod(final Activity activity) {
        View view = activity.getCurrentFocus();
        if (view == null) view = new View(activity);
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
        if (imm == null) return;
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    /**
     * 动态隐藏软键盘
     *
     * @param view 视图
     */
    public static void hideInputMethod(final View view) {
        InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm == null) return;
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    /**
     * 切换键盘显示与否状态
     */
    public static void toggleSoftInput() {
        InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm == null) return;
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_NOT_ALWAYS);
    }

}
